import React, { useState, useMemo } from 'react';
import { Card, Tree, Button, Space, Spin } from 'antd';
import { ApartmentOutlined, PlusOutlined, EditOutlined, ReloadOutlined } from '@ant-design/icons';
import { useDepartmentTree } from '@/hooks/useDepartment';
import type { DataNode } from 'antd/es/tree';
import type { Department } from '@/services/department';

/**
 * 组织架构页面
 * 演示完整的请求流程：组件 -> Hook -> Service -> Request -> 后端
 */
const DepartmentStructure: React.FC = () => {
  // 使用自定义Hook获取部门树形数据
  const { treeData: departmentData, loading, refresh } = useDepartmentTree();
  
  // 展开的节点状态
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);

  /**
   * 将部门数据转换为Tree组件需要的数据格式
   */
  const transformDepartmentToTreeData = (departments: Department[]): DataNode[] => {
    return departments.map((dept) => ({
      title: dept.name, // 部门名称作为节点标题
      key: dept.id.toString(), // 部门ID作为节点key
      children: dept.children ? transformDepartmentToTreeData(dept.children) : undefined, // 递归处理子部门
    }));
  };

  /**
   * 使用useMemo优化树形数据转换，避免不必要的重新计算
   */
  const treeData = useMemo(() => {
    if (!departmentData || departmentData.length === 0) {
      // 如果没有数据，返回模拟数据作为备用
      return [
        {
          title: '总公司',
          key: '0',
          children: [
            {
              title: '技术部',
              key: '0-0',
              children: [
                { title: '前端开发组', key: '0-0-0' },
                { title: '后端开发组', key: '0-0-1' },
                { title: '测试组', key: '0-0-2' },
              ],
            },
            {
              title: '市场部',
              key: '0-1',
              children: [
                { title: '市场推广组', key: '0-1-0' },
                { title: '品牌策划组', key: '0-1-1' },
              ],
            },
          ],
        },
      ];
    }
    return transformDepartmentToTreeData(departmentData);
  }, [departmentData]);

  /**
   * 默认展开所有节点
   */
  const defaultExpandedKeys = useMemo(() => {
    const getAllKeys = (nodes: DataNode[]): React.Key[] => {
      const keys: React.Key[] = [];
      const traverse = (nodeList: DataNode[]) => {
        nodeList.forEach((node) => {
          keys.push(node.key);
          if (node.children) {
            traverse(node.children);
          }
        });
      };
      traverse(nodes);
      return keys;
    };
    return getAllKeys(treeData);
  }, [treeData]);

  // 当树形数据变化时，自动展开所有节点
  React.useEffect(() => {
    setExpandedKeys(defaultExpandedKeys);
  }, [defaultExpandedKeys]);

  /**
   * 处理添加部门按钮点击事件
   */
  const handleAddDepartment = () => {
    console.log('添加部门功能开发中...');
    // TODO: 实现添加部门的弹窗和逻辑
  };

  /**
   * 处理编辑架构按钮点击事件
   */
  const handleEditStructure = () => {
    console.log('编辑架构功能开发中...');
    // TODO: 实现编辑架构的功能
  };

  /**
   * 处理刷新按钮点击事件
   * 使用Hook提供的refresh方法
   */
  const handleRefresh = () => {
    refresh();
  };

  return (
    <div>
      <Card 
        title={
          <Space>
            <ApartmentOutlined />
            <span>组织架构</span>
          </Space>
        }
        extra={
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
            loading={loading}
            size="small"
          >
            刷新
          </Button>
        }
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          {/* 操作按钮区域 */}
          <Space>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={handleAddDepartment}
            >
              添加部门
            </Button>
            <Button 
              icon={<EditOutlined />}
              onClick={handleEditStructure}
            >
              编辑架构
            </Button>
          </Space>
          
          {/* 组织架构树形展示区域 */}
          <Spin spinning={loading} tip="正在加载组织架构数据...">
            <Tree
              showLine={{ showLeafIcon: false }} // 显示连接线，不显示叶子节点图标
              expandedKeys={expandedKeys} // 受控的展开节点
              onExpand={setExpandedKeys} // 展开/收起节点时的回调
              treeData={treeData} // 树形数据
              style={{ minHeight: '400px' }} // 设置最小高度
            />
          </Spin>
        </Space>
      </Card>
    </div>
  );
};

export default DepartmentStructure;